import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {Pattern} from "../../public/service/pattern";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {PagesService} from "../../services/pages.service";

@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {
  public validateForm: FormGroup = this.fb.group({
    account: [null, Validators.compose([Validators.required, Validators.pattern(Pattern.account)])],
    realName: [null, Validators.compose([Validators.required])],//真实姓名
    password: [null, Validators.compose([Validators.required])],
    pinPassword: [null, [Validators.required]],
    phone: [null, Validators.compose([Validators.required, Validators.pattern(Pattern.mobile)])],//	手机号
    referenceAccount: [null, Validators.compose([Validators.required])],//推荐人账户
  });//注册的表单
  public isReferenceAccount: boolean = false;
  private isLoading: boolean = false;

  constructor(private fb: FormBuilder,
              public navCtrl: NavController,
              public navParams: NavParams,
              private pagesService: PagesService) {
  }

  ionViewDidLoad() {
    let url = location.href;
    if (url.indexOf('=') > 0) {
      this.isReferenceAccount = true;
      let referenceAccount = url.substring(url.indexOf('=') + 1);
      this.validateForm.patchValue({referenceAccount: referenceAccount})
    }
  }

  register($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    // register
    if (this.isLoading) return;
    else this.isLoading = true;
    me.pagesService.register(me.validateForm.value).then((data: string) => {
      me.navCtrl.setRoot('LoginPage');
    }).catch(err => {
      this.isLoading = false;
    })
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
